package mathive.client.panels;

import mathive.client.PanelHandler;
import mathive.client.UserHandler;
import mathive.client.UserService;
import mathive.client.UserServiceAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class ChangePassPanel {
	private static final UserServiceAsync SERVICE = GWT.create(UserService.class);

	private VerticalPanel mainPanel = new VerticalPanel();
	private PasswordTextBox oldPassword = new PasswordTextBox();
	private PasswordTextBox password = new PasswordTextBox();
	private Label old_label = new Label("Old password");
	private Label pass_label = new Label("New password");
	private Button changeButton = new Button("Save");
	
	public ChangePassPanel() {
		// Listen for mouse events on the register button.
		changeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				SERVICE.ChangePassword(
						UserHandler.singleton.getSessionID(),
						oldPassword.getText(),
						password.getText(),
						new ChangePassResponse());
			}
		});
		
		initialize();
	}
	
	public Widget getPanel(){
		mainPanel.clear();
		initialize();
		return mainPanel;
	}
	
	private void initialize(){		
		
		mainPanel.add(new HTML("<h1>Change Password</h1>"));
		mainPanel.add(old_label);
		mainPanel.add(oldPassword);
		mainPanel.add(pass_label);
		mainPanel.add(password);
		mainPanel.add(changeButton);
		mainPanel.setCellHorizontalAlignment(changeButton, HasHorizontalAlignment.ALIGN_RIGHT);
		
	}
	
	private class ChangePassResponse implements AsyncCallback<Boolean> {
		@Override
		public void onFailure(Throwable caught) {
		}

		@Override
		public void onSuccess(Boolean result) {
			
			if (result.booleanValue()) {
				UserHandler.singleton.logout();
				PanelHandler.showHome();
			} else {
				mainPanel.add(new Label("Wrong password"));
			}
		}
	}
}

